package com.nameless.aspect;

import com.nameless.annotation.HasPermission;
import com.nameless.exception.PermissionException;
import com.nameless.util.JwtUtil;
import com.nameless.util.WebUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author keluoyisi
 * @program: tong-parent
 * @description:
 * @date 2023-02-24 10:53:29
 */

@Aspect
@Component
public class PermissionAspect {
    @Pointcut(value = "@annotation(com.nameless.annotation.HasPermission)")
    public void pointCut(){}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        HasPermission annotation = method.getAnnotation(HasPermission.class);
        if (annotation!=null){
            String value = annotation.value();
            String token = WebUtils.getRequest().getHeader("token");
            Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
            List<String> permission = (List<String>) tokenChaim.get("permission");
            boolean b = permission.stream().anyMatch(item -> item.equals(value));
            if (!b){
                throw new PermissionException("权限不足");
            }
        }
        return joinPoint.proceed();
    }


}
